package com.framework.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.framework.common.auto.ThreadLocalUtils;
import com.framework.common.utils.SnowflakeIdWorker;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理数据库通用字段新增/编辑复制
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        fillValue(metaObject, "id", SnowflakeIdWorker.nextId());
        fillValue(metaObject, "corpId", ThreadLocalUtils.getCorpId());
        fillValue(metaObject, "createId", ThreadLocalUtils.getUserId());
        fillValue(metaObject, "createDate", new Date());
        fillValue(metaObject, "deleteState", false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        fillValue(metaObject, "updateId", ThreadLocalUtils.getUserId());
        fillValue(metaObject, "updateDate", new Date());
    }

    private void fillValue(MetaObject metaObject, String fieldName, Object val) {
        if (!metaObject.hasGetter(fieldName)) {
            return;
        }
        Object fieldVal = getFieldValByName(fieldName, metaObject);
        if (fieldVal == null) {
            setFieldValByName(fieldName, val, metaObject);
        }
    }
}
